package org.jeecg.modules.cosmetic.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.cosmetic.entity.TToxicologicalEdible;
import org.jeecg.modules.cosmetic.model.dto.ToxEdibleDTO;
import org.jeecg.modules.cosmetic.model.vo.ToxEdibleVO;
import org.jeecg.modules.cosmetic.service.ITToxicologicalEdibleService;
import org.jeecg.modules.cosmetic.utils.CurrentUserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ToxicologicalEdibleHandler {

    @Resource
    private ITToxicologicalEdibleService toxicologicalEdibleService;

    /**
     * 保存和更新可食用信息
     * @param vo
     * @return
     */
    public Result<?> saveOrUpdate(ToxEdibleVO vo) {
        Optional.ofNullable(vo.getType()).orElseThrow(() -> new JeecgBootException("数据类型不能为空：1-GRAS，2-食品添加；3-药食同源；4-新资源食品；5-其它!"));
        TToxicologicalEdible tToxicologicalEdible = new TToxicologicalEdible();
        BeanUtils.copyProperties(vo, tToxicologicalEdible);
        tToxicologicalEdible.setUpdateBy(CurrentUserUtil.authInfo().getName());
        if (ObjectUtils.isEmpty(vo.getId())) {
            tToxicologicalEdible.setCreateBy(CurrentUserUtil.authInfo().getName());
            return Result.ok(toxicologicalEdibleService.save(tToxicologicalEdible));
        } else {
            return  Result.ok(toxicologicalEdibleService.updateById(tToxicologicalEdible));
        }
    }

    /**
     * 根据毒理数据ID查询数据
     * @param id
     * @return
     */
    public List<ToxEdibleDTO> getEdible(Long id) {
        List<TToxicologicalEdible> list = toxicologicalEdibleService.list(new LambdaQueryWrapper<TToxicologicalEdible>().eq(TToxicologicalEdible::getToxId, id));
        List<ToxEdibleDTO> dtoList = Lists.newArrayList();
        return list.stream().map(m -> {
            ToxEdibleDTO dto = new ToxEdibleDTO();
            BeanUtils.copyProperties(m, dto);
            return dto;
        }).collect(Collectors.toCollection(() -> dtoList));
    }

    /**
     * 根据ID删除数据
     * @param id
     * @return
     */
    public boolean delete(Long id) {
        return toxicologicalEdibleService.removeById(id);
    }
}
